package cn.shop.merchant.service;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.shop.transcation.ipWhitelistModule.entity.IpWhitelist;
import cn.shop.transcation.ipWhitelistModule.mapper.IpWhitelistMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import static cn.shop.utils.constant.Constant.UID;

/**
 * @author : 李一涵
 * @date : Created in 2021-11-8 17:10
 * @description : 黑名单service
 */
@Service
public class IpWhitelistService extends BaseServiceImpl<IpWhitelistMapper, IpWhitelist> {

	/**
	 * 设置白名单
	 *
	 * @param ipList
	 * @return
	 * @author jzw
	 * @since 2022/2/23 11:19
	 */
	public boolean insert(List<String> ipList) {
		// 删除当前用户下所有白名单
		LambdaQueryWrapper<IpWhitelist> query = Wrappers.lambdaQuery();
		Long userId = StpUtil.getSession().getLong(UID);
		query.eq(IpWhitelist::getUserId, userId);
		baseMapper.delete(query);
		ipList.removeIf(StrUtil::isBlank);
		List<IpWhitelist> collect = ipList.stream().map(e -> {
			IpWhitelist ipWhitelist = new IpWhitelist();
			ipWhitelist.setId(IdWorker.getId());
			ipWhitelist.setIp(e);
			return ipWhitelist;
		}).collect(Collectors.toList());
		//添加白名单
		return SqlHelper.retBool(baseMapper.save(collect, userId));
	}

}
